<?php
namespace Ptime3\Functions;
class JoinData
{
	public static function user($array,$userTag="user")
	{
		$env = function_exists("env")?env("APP_ENV"):"dev";
		if($env == "product"){
			$dbHost = env("DB_HOST");
			$dbUser = env("DB_USERNAME");
			$dbPassword = env("DB_PASSWORD");
			$dbName = "ptime3user";
		}else{
			$dbHost	 = "192.168.2.103";
			$dbUser	 = "root";
			$dbPassword= "xiaobaitu2";
			$dbName	 = "ptime3user";
		}

		$userIdTag   = $userTag."_id";
		$userNameTag = $userTag."_name";
		$userIconTag = $userTag."_icon";

		if(empty($array[0]->$userIdTag))
			return $array;

		$userIds = [];
		$userHash = [];
		foreach ($array as $key => $value) {
			$userIds[] = $value->$userIdTag;
		}

		$userIdsStr = implode(",", $userIds);

		// @$con = mysqli_connect($dbHost,$dbUser,$dbPassword,$dbName);
		// if (!mysqli_connect_errno()){

		// 	mysqli_set_charset($con,"utf8");

		// 	$result     = mysqli_query($con,"SELECT id,name,icon FROM ur_user WHERE id IN ($userIdsStr);");

		// 	$userHash   = [];
		// 	while($row  = mysqli_fetch_array($result))
		// 	{
		// 		$userHash[$row["id"]] = $row;
		// 	}
		// 	mysqli_close($con);
		// }
		$dsn="mysql:host=$dbHost;dbname=$dbName;charset=utf8";
		try {
		    $dbh = new \PDO($dsn, $dbUser, $dbPassword,["cah"]); //初始化一个PDO对象

		    $result = $dbh->query("SELECT id,name,icon FROM ur_user WHERE id IN ($userIdsStr);");

		    foreach($result as $row) {
		        $userHash[$row["id"]] = $row;
		    }

		    $dbh = null;
		} catch (\PDOException $e) {
		    //die ("Error!: " . $e->getMessage() . "<br/>");
		}

		foreach ($array as $key => $value) {
			$value->$userNameTag = isset($userHash[$value->$userIdTag])?$userHash[$value->$userIdTag]["name"]:"";
			$value->$userIconTag = isset($userHash[$value->$userIdTag])?$userHash[$value->$userIdTag]["icon"]:"";
		}

		return $array;
	}


}
